package cn.com.utt.gateway.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.com.utt.common.log.SaveIpaddress;
import cn.com.utt.common.mapper.LockIpMapper;
import cn.com.utt.common.service.UserService;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.LockIp;
import cn.com.utt.common.vo.Role;
import cn.com.utt.common.vo.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Service("jwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {

	@Autowired
	private UserService userService;
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;
	
	@Autowired
	private LockIpMapper lockIpMapper;

	/**
	 * 根据用户名获取登录用户信息
	 * 
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
		System.out.println("loadUserBylogin");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		User user = userService.queryByUsernameOrEmail(login);
		if (user == null) {
			throw new UsernameNotFoundException(messageSourceUtil.getMessage(Tips.NoUsername));
		}
		if (user.getDomain() == null){
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		    HttpServletRequest request = servletRequestAttributes.getRequest();
		    user.setDomain(request.getServerName());
		    userService.update(user);
		}
		
		if (user.getDomain().equals("cloud.anphat.vn")){
			String ip = SaveIpaddress.getThreadLocal().get();
			LockIp lockIp = lockIpMapper.queryByIp(ip);
			if (lockIp != null){
				Date lockTime = lockIp.getLockTime();
				if (lockIp.getFailtimes() >= 5){
					long ts = 0L;
					ts = lockTime.getTime();
					if ((System.currentTimeMillis() - ts) / (1000 * 60) >= 10) {
						lockIpMapper.deleteByIp(ip);
					}else{
						throw new UsernameNotFoundException(messageSourceUtil.getMessage(Tips.LockIp).replaceAll("#", ip).replaceAll("\\*", df.format(lockTime.getTime() + 600000)));
					}
				}
			}
		}
		
		List<Role> roles = userService.queryRolesById(user.getId());
		Date lastfail = user.getLastfail();
		if (lastfail != null && !df.format(lastfail).equals(df.format(new Date())) && user.getFailtimes() != 0) {
			user.setFailtimes((short) 0);
			userService.update(user);
		}
		if (lastfail != null) {
			if (user.getFailtimes() >= 5) {
				long ts = 0L;
				ts = lastfail.getTime();
				if ((System.currentTimeMillis() - ts) / (1000 * 60) > 120) {
					user.setFailtimes((short) 0);
					user.setLastfail(null);
					userService.update(user);
				} else {
					throw new UsernameNotFoundException(messageSourceUtil.getMessage(Tips.LockAccount));
				}
				
			}
		}
		user.setAuths(roles);
		return user;
	}
	
	public static void main(String[] args) throws ParseException {
		Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-04-20 17:42:30");
		long ts = 0L;
		ts = date.getTime();
		System.out.println(System.currentTimeMillis() - ts);
		System.out.println((System.currentTimeMillis() - ts) / (1000 * 60));
		
	}
}
